<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h1>点击获取游戏信息</h1>
  <form id="form" action="">
    <input type="text" name="name">
    <input type="text" name="time">
    <input type="text" name="publisher">
    <button id="btn">点击获取</button>
  </form>
  <ul id="ul"></ul>
  <script>
    // 获取元素
    const oform = document.getElementById('form')
    const oname = document.querySelector('#form input[name=name]')
    const otime = document.querySelector('#form input[name=time]')
    const opublisher = document.querySelector('#form input[name=publisher]')
    const btn = document.querySelector('#btn')
    const oul = document.querySelector('#ul')

    // 绑定提交事件
    oform.onsubmit = function () {
      // 获取文本框的内容
      const nameValue = oname.value
      const timeValue = otime.value
      const publisher = opublisher.value

      // 创建ajax实例
      const xhr = new XMLHttpRequest()

      // 打开路径
      xhr.open('POST', '/game', true)

      // 发送请求
      // 由于post传参的方式有多种,所以需要设置请求头
      xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8")
      xhr.send(JSON.stringify({
        name: nameValue,
        time: timeValue,
        publisher: publisher
      }))

      // 绑定事件
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status <= 299) {
          const data = JSON.parse(xhr.responseText).data
          console.log(data);
        }
      }
      return false
    }
  </script>
</body>

</html>